package me.cxlr.shaopinghelper.view.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import me.cxlr.shaopinghelper.R;
import me.cxlr.shaopinghelper.constants.Constants;
import me.cxlr.shaopinghelper.databinding.FragmentMainBinding;
import me.cxlr.shaopinghelper.resource.Resource;
import me.cxlr.shaopinghelper.util.MmkvUtil;
import me.cxlr.shaopinghelper.util.ToastUtil;

/**
 * 主页
 *
 * @author ShanLunZhi
 */
public class MainFragment extends Fragment {
    private FragmentMainBinding viewBinding;
    private PowerManager powerManager;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        powerManager = (PowerManager) requireActivity().getSystemService(Context.POWER_SERVICE);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        viewBinding = FragmentMainBinding.inflate(inflater, container, false);
        return viewBinding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();

        this.loadToolbar();
        this.loadSettings();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (viewBinding != null) {
            viewBinding = null;
        }
    }

    /**
     * 初始化Toolbar
     */
    private void loadToolbar() {
        viewBinding.fmToolbar.setTitle(R.string.toolbar_title_main_fragment);
    }

    /**
     * 初始化设置
     */
    private void loadSettings() {
        // 说明
        viewBinding.fmCvsmwTip.setImage(R.drawable.icon_tips);
        viewBinding.fmCvsmwTip.setTitle(getString(R.string.tips_title));
        viewBinding.fmCvsmwTip.flush();
        viewBinding.fmCvsmwTip.setMessage(getString(R.string.tips_msg_1));
        viewBinding.fmCvsmwTip.setMessage(getString(R.string.tips_msg_2));
        viewBinding.fmCvsmwTip.setMessage(getString(R.string.tips_msg_3));

        // 主题
        viewBinding.fmCvsmwTheme.setVisibility(View.GONE);
        viewBinding.fmCvsmwTheme.setImage(R.drawable.icon_theme);
        viewBinding.fmCvsmwTheme.setTitle(getString(R.string.settings_theme_title));
        viewBinding.fmCvsmwTheme.setMessage(Resource.getResourceCurrentThemeMsg(MmkvUtil.decodeInt("settings_theme", Constants.SETTING_THEME_BY_SYSTEM)));
        viewBinding.fmCvsmwTheme.setOnClickListener(v -> ToastUtil.show(requireContext(), "开发中", ToastUtil.LENGTH_LONG));

        // 权限->电池优化
        viewBinding.fmCvsmwBattery.setVisibility(View.GONE);
        viewBinding.fmCvsmwBattery.setImage(R.drawable.icon_battery);
        viewBinding.fmCvsmwBattery.setTitle(getString(R.string.settings_battery_title));
        viewBinding.fmCvsmwBattery.setOnClickListener(v -> {
            @SuppressLint("BatteryLife") Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + Constants.PACKAGE_NAME));
            startActivity(intent);
        });
        boolean batteryPermission = powerManager.isIgnoringBatteryOptimizations(Constants.PACKAGE_NAME);
        if (batteryPermission) {
            viewBinding.fmCvsmwBattery.setMessage(getString(R.string.settings_battery_summary_on));
        } else {
            viewBinding.fmCvsmwBattery.setMessage(getString(R.string.settings_battery_summary_off));
        }

        // 使用通知填满通知栏    todo
        viewBinding.fmCvswNotice.setTitle("发送通知填满通知栏");

        // 调整亮度
        viewBinding.fmCvsTuneBrightness.setTitle(getString(R.string.settings_tune_brightness_title));
        int brightness = MmkvUtil.decodeInt("settings_brightness", 0);
        viewBinding.fmCvsTuneBrightness.setMessage(String.valueOf(brightness));
        viewBinding.fmCvsTuneBrightness.setSeekBarMinAndMax(0, 255);
        viewBinding.fmCvsTuneBrightness.setProgress(brightness);
        viewBinding.fmCvsTuneBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                viewBinding.fmCvsTuneBrightness.setMessage(String.valueOf(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                MmkvUtil.encode("settings_brightness", seekBar.getProgress());
            }
        });

        // 模式
        viewBinding.fmCvsmwMode.setImage(R.drawable.icon_mode);
        viewBinding.fmCvsmwMode.setTitle(getString(R.string.settings_mode_title));
        viewBinding.fmCvsmwMode.setMessage(Resource.getShaoPingMode(MmkvUtil.decodeInt("settings_mode", Constants.SETTING_MODE_EBOOK)));
        viewBinding.fmCvsmwMode.setOnClickListener(v -> selectShaoPingMode());

        // 开始
        viewBinding.fmCvsmwStart.setTitle("开始");
        viewBinding.fmCvsmwStart.setMessage("请点击这里开始 :)");
        viewBinding.fmCvsmwStart.setOnClickListener(v -> {
            NavHostFragment.findNavController(MainFragment.this).navigate(R.id.action_mainFragment_to_ebookFragment);
        });
    }

    /**
     * 选择烧屏模式
     * String[] items = new String[]{getString(R.string.settings_mode_ebook), getString(R.string.settings_mode_zjdy)};
     * int[] values = new int[]{Constants.SETTING_MODE_EBOOK, Constants.SETTING_MODE_ZJDY};
     */
    private void selectShaoPingMode() {

        String[] items = new String[]{getString(R.string.settings_mode_ebook)};
        int[] values = new int[]{Constants.SETTING_MODE_EBOOK};

        AlertDialog alertDialog = new AlertDialog.Builder(requireContext())
                .setTitle(getString(R.string.settings_mode_title))
                .setItems(items, (dialog, which) -> {
                    MmkvUtil.encode("settings_mode", values[which]);
                    viewBinding.fmCvsmwMode.setMessage(Resource.getShaoPingMode(MmkvUtil.decodeInt("settings_mode", Constants.SETTING_MODE_EBOOK)));
                    dialog.dismiss();
                })
                .setPositiveButton("关闭", (dialog, which) -> dialog.dismiss())
                .create();
        alertDialog.show();
    }
}